package phapp.action.uploads;

import static javacommon.util.Struts2JsonHelper.outJson;
import static javacommon.util.Struts2JsonHelper.myWriterJson;
import static javacommon.util.Struts2JsonHelper.outStringOld;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javacommon.base.BaseStruts2Action;
import javacommon.util.DateUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import phapp.model.custom.Custom;
import phapp.service.common.CommonUtils;
import phapp.service.common.QfdException;


/**
 * @描述：文件上传 Action
 * @CopyRright 
 * @创建人：
 * @日期
 * @版本号：
*/
 
public class AjaxUploadAction extends BaseStruts2Action {
	
	private static Logger log = Logger.getLogger(AjaxUploadAction.class);
	
	private static final String FILE_PATH_IN_SERVER = "xheditorUpload";
	
	private File file;
	private String fileFileName;
	private String fileContentType;

	
	public File getFile() {
		return file;
	}
	public void setFile(File file) {
		this.file = file;
	}
	public String getFileFileName() {
		return fileFileName;
	}
	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}
	public String getFileContentType() {
		return fileContentType;
	}
	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}
	
	//多文件上传 
	public void myUpload(MultipartHttpServletRequest multipartRequest,HttpServletRequest request, HttpServletResponse response)  {
		log.debug("---------------------------------------upload----------");
		response.setContentType("text/html;charset=UTF-8");
		Map<String, Object> result = new HashMap<String, Object>();
		//获取多个file
		List list = new ArrayList();
		String json_str="";
		for (Iterator it = multipartRequest.getFileNames(); it.hasNext();) {
		      String key = (String) it.next();
		      MultipartFile imgFile = multipartRequest.getFile(key);
		      if (imgFile.getOriginalFilename().length() > 0) {
		        String fileName = imgFile.getOriginalFilename();
		        //文件后缀名
		        String extensionName = fileName.substring(fileName.lastIndexOf(".") + 1,fileName.length()); 
		        //新文件名
		        String newfileName =  DateUtil.generateFileName()+"."+extensionName;
		        //改成自己的对象哦！
		        MyUploadFile obj = new MyUploadFile();
		        //Constant.UPLOAD_GOODIMG_URL 是一个配置文件路径
		        try {
		          //String uploadFileUrl = multipartRequest.getSession().getServletContext().getRealPath(Constant.UPLOAD_URL);
		            String dataUrl = DateUtil.getNowShortDate();
		            String uploadUrl = "/upload/"+dataUrl+"/";
		            String uploadFileUrl = multipartRequest.getSession().getServletContext().getRealPath(uploadUrl);
		          File test_file = new File(uploadFileUrl);
		          if(!test_file.exists()){
		              //目录不存在
		              test_file.mkdirs();
		          }
		          long ctm = System.currentTimeMillis(); 
		          
		          File _apkFile = saveFileFromInputStream(imgFile.getInputStream(), uploadFileUrl, newfileName);
		          System.out.println(" uploadFileUrl+ fileName=" + uploadFileUrl+"\""+ newfileName);
		          if (_apkFile.exists()) {
		            FileInputStream fis = new FileInputStream(_apkFile);
		          } else
		            throw new FileNotFoundException("apk write failed:" + fileName);
		          
		          //设置文件POJO ：MyUploadFile属性
		           
		          obj.setFilePath((String)getParamMap().get("msUrl")+uploadUrl+ newfileName); //文件路径
		          obj.setOldName(fileName);  //文件名
		          obj.setNewName(newfileName); //文件名
		          obj.setFileType(extensionName); //文件后缀
		          obj.setFileSize(String.valueOf(_apkFile.length()));//文件大小	          
		          
		          //将obj文件对象添加到list
		          list.add(obj);		         
		        }catch (Exception e) {
		         
		          e.printStackTrace();
		        }
		      }
		}
		
		try{
			result.put("success", true);
			result.put("fileList", list);
		    
		}catch(Exception exe){
			 result.put("success", false);
		    exe.printStackTrace();
		}
		outJson(result);
	}
	public void xx(){
		outJson("{xx}");
	}
	//单文件上传 
	public void oneUpload(@RequestParam(value = "houseMaps") MultipartFile file,HttpServletRequest request, HttpServletResponse response)  {
		log.debug("---------------------------------------oneUpload----------");
		response.setContentType("text/html;charset=UTF-8");
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String,Object>  context = new HashMap<String, Object>();
		MultipartFile imgFile = file;
		String filePath="";
		String json_str="";
		if (imgFile.getOriginalFilename().length() > 0) {
		        String fileName = imgFile.getOriginalFilename();
		        //文件后缀名
		        String extensionName = fileName.substring(fileName.indexOf(".") + 1,fileName.length()); 
		        //改成自己的对象哦！
		        MyUploadFile obj = new MyUploadFile();
		        //Constant.UPLOAD_GOODIMG_URL 是一个配置文件路径
		        try {
		          //String uploadFileUrl = multipartRequest.getSession().getServletContext().getRealPath(Constant.UPLOAD_URL);
		            String dataUrl = DateUtil.getNowShortDate();
		            String uploadUrl = "/upload/"+dataUrl+"/";
		            String uploadFileUrl = request.getSession().getServletContext().getRealPath(uploadUrl);
		          File test_file = new File(uploadFileUrl);
		          if(!test_file.exists()){
		              //目录不存在
		              test_file.mkdirs();
		          }
		           
		          File _apkFile = saveFileFromInputStream(imgFile.getInputStream(), uploadFileUrl, fileName);
		          filePath =  uploadUrl+ fileName ;
		          if (_apkFile.exists()) {
		            FileInputStream fis = new FileInputStream(_apkFile);
		          } else
		            throw new FileNotFoundException("apk write failed:" + fileName);
		          
		          //设置文件POJO ：MyUploadFile属性
		          obj.setFilePath((String)getParamMap().get("msUrl")+filePath); //文件路径
		          obj.setOldName(fileName);  //文件名
		          obj.setNewName(fileName); //文件名
		          obj.setFileType(extensionName); //文件后缀
		          obj.setFileSize(String.valueOf(_apkFile.length()));//文件大小
		          
		          //返回值
		          context.put(SUCCESS, true);
		          context.put("data", obj);
 	          
		        }catch (Exception e) {
		          e.printStackTrace();
		        }
		         		        
		  }
		 
		outJson(context);
		}		
        //保存文件
          private File saveFileFromInputStream(InputStream stream, String path,
              String filename) throws IOException {
            File file = new File(path + "/" + filename);
            FileOutputStream fs = new FileOutputStream(file);
            byte[] buffer = new byte[1024 * 1024];
            int bytesum = 0;
            int byteread = 0;
            while ((byteread = stream.read(buffer)) != -1) {
              bytesum += byteread;
              fs.write(buffer, 0, byteread);
              fs.flush();
            }
            fs.close();
            stream.close();
            return file;
          }
          
          
          
          private String message = "你已成功上传文件";
          public void  executes() throws IOException {
        	  /** 返回结果 JSON 集合 */
        	  Map<String,Object> result = new HashMap<String,Object>();
        	  HttpServletRequest request = ServletActionContext.getRequest();
              String path = request.getSession().getServletContext().getRealPath("");
              String uploadUrl = (null==request.getParameter("uploadUrl")) ? "upload" : request.getParameter("uploadUrl");
              
              String filePath = path+"/"+uploadUrl;
              String webPath = ""+uploadUrl+"";
              try {
            	  String dataUrl = DateUtil.getNowShortDate();  //日期目录
            	  filePath = filePath+"/"+dataUrl ;
            	  webPath = webPath+"/"+dataUrl ;
            	  File test_file = new File(filePath);
		          if(!test_file.exists()){
		              //目录不存在
		              test_file.mkdirs();
		          }
		           
                  File f = this.getFile();
                   
    		      /** 文件后缀名 */
    		      String extensionName = this.getFileFileName();
                  if(this.getFileFileName().endsWith(".exe")){
                      message="对不起,你上传的文件格式不允许!!!";
                      //return ERROR;
                  }
                  //新文件名
  		          String newfileName =  DateUtil.generateFileName()+extensionName;
                  FileInputStream inputStream = new FileInputStream(f);
                  filePath = filePath + "/"+ newfileName;
                  webPath =(String)getParamMap().get("msUrl")+ webPath + "/"+ newfileName;
                  FileOutputStream outputStream = new FileOutputStream(filePath);
                  byte[] buf = new byte[1024];
                  int length = 0;
                  while ((length = inputStream.read(buf)) != -1) {
                      outputStream.write(buf, 0, length);
                  }
                  inputStream.close();
                  outputStream.flush();
              } catch (IOException e) {
                  e.printStackTrace();
                  message = "对不起,文件上传失败了!!!!";
              }catch(Exception exe){
            	  exe.printStackTrace();
              }
             
              result.put("success", true);
      		  result.put("url",webPath);
      		   outStringOld("{\"success\":true,\"url\":\""+webPath+"\"}");
        	  //myWriterJson(result);
          }
          
          
          
          
}
